package com.yourname.myapplication.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.yourname.myapplication.database.AppDatabase
import android.content.Context
import android.util.Log
import com.yourname.myapplication.model.User
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class RegisterViewModel(context: Context) : ViewModel() {
    // 获取数据库实例
    private val appDatabase = AppDatabase.getInstance(context)

    // 注册方法，接收用户名和密码进行注册操作
    fun registerUser(username: String, password: String, onSuccess: () -> Unit, onFailure: (String) -> Unit) {
        if (!isValidUsername(username)) {
            Log.d("RegisterViewModel", "Invalid password")
            onFailure("用户名不符合规则，长度应在 3 到 20 个字符之间")
            return
        }
        if (!isValidPassword(password)) {
            Log.d("RegisterViewModel", "Invalid username")
            onFailure("密码不符合规则，长度应至少为 6 个字符")
            return
        }
        viewModelScope.launch {
            try {
                val user = User(username = username, password = password)
                withContext(Dispatchers.IO) {
                    appDatabase.userDao().insertUser(user)
                }
                withContext(Dispatchers.Main) {
                    onSuccess()
                }
            } catch (e: Exception) {
                Log.e("RegisterViewModel", "Registration failed: ${e.message}", e)
                withContext(Dispatchers.Main) {
                    onFailure("注册失败：${e.message}")
                }
            }
        }
    }

    // 简单的用户名验证规则，可按需调整
    private fun isValidUsername(username: String): Boolean {
        return username.length in 3..20
    }

    // 简单的密码验证规则，可按需调整
    private fun isValidPassword(password: String): Boolean {
        return password.length >= 6
    }
}